// import type { ProvinceEnum, CityEnum, AreaEnum } from '~/store/global.typings'
import type {
  DrawPatternType,
  MapToolBarPropsType,
  MapToolBarStateType,
  // MapToolBarDistrictSearchResultType,
  MapToolBarLngLatType
} from './typings'
import { defineComponent, reactive, watch } from 'vue'
// import { useStore } from 'vuex'
import { isArray } from 'lodash'
import {
  ElSpace,
  ElPopover,
  ElTooltip,
  // ElTabs,
  // ElTabPane,
  ElButton,
  // ElLink,
  ElDescriptions,
  ElDescriptionsItem,
  // ElSkeleton,
  ElIcon
} from 'element-plus'
import AliIcon from '../AliIocn'
// import useVuexGetters from '~/hooks/useVuexGetters'
import useToolbarEventHook from './ToolbarButtonsEvent'
import styles from './index.module.scss'

export default defineComponent({
  name: 'MapToolbar',
  props: ['visible', 'mapRef', 'aMapRef', 'screenDomRef', 'center', 'strokeColor'],
  // emits: ['changePatternItemPath'],
  setup(props: MapToolBarPropsType, { /* emit, */ expose }) {
    // const store = useStore()
    const [eventState, eventMethod] = useToolbarEventHook(props, handleDrawPolylineOnPolylineObject)
    const state = reactive<MapToolBarStateType>({
      fullScreen: false,
      activeRegionTabKey: 'province',
      loading: false,
      drawPatterns: {}
    })
    // const globalState = useVuexGetters('global', [
    //   'provinceSelectList',
    //   'citySelectList',
    //   'areaSelectList'
    // ])

    // 根据传入图案绘制多条线段在线段对象里
    function handleDrawPolylineOnPolylineObject(drawPattern: Record<string, any>) {
      const { strokeColor } = props
      // 当已经配置过图案时
      if (state.drawPatterns[strokeColor!]) {
        const path = drawPattern
          .getPath()
          ?.reduce((arr: [number, number][], item: MapToolBarLngLatType) => {
            if (item.lat !== 0 && item.lng !== 0) {
              arr.push([item?.lng, item?.lat])
            }
            return arr
          }, [])
        const pattern = state.drawPatterns[strokeColor!].pattern
        const patternPath = state.drawPatterns[strokeColor!].pattern?.getPath()
        // 如果有图案 则销毁新绘制的
        if (pattern) {
          drawPattern.hide()
          // drawPattern.destroy()
        }
        // 没有一条直线有图形对象的判断
        if (!pattern.getExtData()?.visible) {
          pattern.setPath(path)
          pattern.show()
          pattern.setExtData({ visible: true })
        } else if (state.drawPatterns[strokeColor!].type === 'polyline') {
          // 只有一条线 改变其数据结构
          state.drawPatterns[strokeColor!].type = 'multiPolyline'
          pattern.setPath([patternPath, path])
        } else {
          // 多条线 只需要在原有的追加
          pattern.setPath([...patternPath, path])
        }
        // 使用完画的线后及时销毁这条线
        drawPattern.hide()
        // drawPattern.destroy()
      } else {
        drawPattern?.setOptions({
          // strokeWeight: (drawPattern?.getOptions()?.strokeWeight || 2) - 2
          strokeWeight: drawPattern?.getOptions()?.strokeWeight || 2
        })
        // 没有配置过图案
        state.drawPatterns[strokeColor!] = {
          type: 'polyline',
          pattern: drawPattern
        }
      }
    }

    // 点击省级时替换市级列表并赋值
    // const handleChangeActiveProvince = (item: ProvinceEnum) => {
    //   store.commit('global/SET_CITY_SELECT_LIST', item?.children || [])
    //   state.activeRegionTabKey = 'city'
    //   state.activeProvince = item
    //   state.activeCity = undefined
    //   state.activeArea = undefined
    // }

    // 点击市级时替换区级列表并赋值
    // const handleChangeActiveCity = (item: CityEnum) => {
    //   store.commit('global/SET_AREA_SELECT_LIST', item?.children || [])
    //   state.activeRegionTabKey = 'area'
    //   state.activeCity = item
    //   state.activeArea = undefined
    // }

    // 点击区级时赋值
    // const handleChangeActiveArea = (item: AreaEnum) => {
    //   const { mapRef, aMapRef } = props
    //   state.activeArea = item
    //   new aMapRef!.value.DistrictSearch({
    //     subdistrict: 0, // 获取边界不需要返回下级行政区
    //     extensions: 'all', // 返回行政区边界坐标组等具体信息
    //     level: 'district' // 查询行政级别为 省、市、区
    //   }).search(item.districtName, (status: string, result: MapToolBarDistrictSearchResultType) => {
    //     state.disProvince && state.disProvince.setMap(null)
    //     state.disProvince = new aMapRef.value.DistrictLayer.Province({
    //       depth: 2,
    //       adcode: result.districtList[0].adcode,
    //       opacity: 0.5,
    //       styles: {
    //         fill: '#80d8ff',
    //         'county-stroke': '#0091ea'
    //       }
    //     })
    //     state.disProvince!.setMap(mapRef!.value)
    //     const center = result.districtList[0].center
    //     mapRef!.value.panTo([center?.lng, center?.lat], 30)
    //   })
    // }

    // 切换已选工具icon回调
    const handleToggleToolBarKey = (activeKey: MapToolBarStateType['activeToolbarKey']) => {
      handleClearCurrentOption(state.activeToolbarKey)
      state.activeToolbarKey = state.activeToolbarKey === activeKey ? undefined : activeKey
    }

    // 全屏回调
    const handleToggleToolBarFullFrameKey = () => {
      state.fullScreen = !state.fullScreen
      eventMethod.handleMapBindFullFrame(state.fullScreen, () => {
        state.fullScreen = false
      })
    }

    // 清除当前操作状态
    const handleClearCurrentOption = (
      beforeToolbarKey: MapToolBarStateType['activeToolbarKey']
    ) => {
      // 如果鼠标工具栏目前启用 则关闭
      if (eventState.mouseTool) {
        // 清除上一步没保存绘制的图像
        eventMethod.handleClearMouseTool(true)
        // 如果是剪切功能则需要去发送给父组建校验路径的绑定关系
        if (beforeToolbarKey === 'crop') {
          // const { strokeColor } = props
          // const patternInfo = state.drawPatterns[strokeColor!]
          // const patternPath = patternInfo?.pattern?.getPath()
          // if (patternInfo.type === 'polyline' && patternPath?.length) {
          //   emit('changePatternItemPath', patternPath)
          // } else {
          //   emit('changePatternItemPath', patternPath?.flat?.() || [])
          // }
        } else {
          // 不是剪切的话鼠标工具只有画图  画图需要清除文案提示
          eventMethod.handleClearTextPattern()
        }
      }
      // 如果编辑栏启用则关闭
      if (eventState.patternEditor) {
        const { strokeColor } = props
        const patternInfo = state.drawPatterns[strokeColor!]
        eventMethod.handleCloseEditPattern(patternInfo?.pattern)
        // 校验编辑后的折线是否还存在
        const patternPath = patternInfo?.pattern?.getPath()
        // 如果编辑后没有折线则修改其类型
        if (!patternPath?.length && patternInfo.type === 'multiPolyline') {
          patternInfo.type = 'polyline'
        } else {
          // 查询数组层级 如果层级与type不匹配则 修改type
          let level = 0
          let levelFirstItem = patternPath
          while (isArray(levelFirstItem)) {
            levelFirstItem = levelFirstItem[0]
            ++level
          }
          // 如果修改编辑了后是单个图形 但类型是多个则改成单个
          if (level === 1 && patternInfo.type === 'multiPolyline') {
            patternInfo.type = 'polyline'
          }
        }
        // if (patternInfo.type === 'polyline' && patternPath?.length) {
        //   emit('changePatternItemPath', patternPath)
        // } else {
        //   emit('changePatternItemPath', patternPath?.flat?.() || [])
        // }
      }
      // 如果连线对象存在则清楚并将路径存入当前线路里
      if (eventState.contactLinkPattern) {
        const { mapRef } = props
        // 连线必须有至少两个点才能存入连线数据中
        const contactLinkPatternPath = eventState.contactLinkPattern?.getPath()
        if (contactLinkPatternPath && contactLinkPatternPath?.length >= 2) {
          handleDrawPolylineOnPolylineObject(eventState.contactLinkPattern)
        } else {
          eventState.contactLinkPattern.hide()
          // eventState.contactLinkPattern.destroy()
        }
        eventState.contactLinkPattern = undefined
        mapRef.value.clearEvents('rightclick')
        // 清除连线文案提示
        eventMethod.handleClearTextPattern()
      }
    }

    // 点击绘制图案的回调
    const handleClickDrawPattern = () => {
      handleToggleToolBarKey('draw')
      if (state.activeToolbarKey === 'draw') eventMethod.handleMapDrawPattern()
    }

    // 编辑当前折线
    const handleClickEditPattern = () => {
      handleToggleToolBarKey('editGraphics')
      const { strokeColor } = props
      // 不存在当前图层或者当前图层不展示时不启用编辑效果
      if (
        state.activeToolbarKey === 'editGraphics' &&
        state.drawPatterns[strokeColor!] &&
        state.drawPatterns[strokeColor!]?.pattern?.getExtData()?.visible
      )
        eventMethod.handleMapEditPattern(state.drawPatterns[strokeColor!]?.pattern)
    }

    // 剪切当前折线
    const handleClickCropPattern = () => {
      handleToggleToolBarKey('crop')
      const { strokeColor } = props
      if (state.activeToolbarKey === 'crop' && state.drawPatterns[strokeColor!])
        eventMethod.handleMapCropPattern(state.drawPatterns[strokeColor!], handleToggleToolBarKey)
    }

    // 新建连线的折线
    const handleClickContactPattern = () => {
      handleToggleToolBarKey('contactLink')
      if (state.activeToolbarKey === 'contactLink') {
        eventMethod.handleCreateMouseFollowText()
        eventMethod.handleMapContactLinkPattern()
      }
    }

    // 初始化图案绘制
    const handleInitDrawPattern = (
      strokeColor: string,
      phase: { type: DrawPatternType['type']; coordinates: [number, number][] }
    ) => {
      if ((phase.type === 'polyline' || phase.type === 'multiPolyline') && phase.coordinates) {
        state.drawPatterns[strokeColor] = {
          type: phase.type,
          pattern: eventMethod.handleInitPolylinePattern(strokeColor, phase.coordinates)
        }
      }
    }

    // 删除对应的图案绘制
    const handleDeletePattern = (strokeColor: string) => {
      // 如果当前工具栏还存在操作则关闭当前工具栏的操作后再删除
      if (state.activeToolbarKey) handleToggleToolBarKey(undefined)
      // 如果当前折线图案存在顺带清除折线图案
      if (state.drawPatterns[strokeColor]?.pattern) {
        state.drawPatterns[strokeColor].pattern.hide()
        state.drawPatterns[strokeColor].pattern.destroy()
      }
      delete state.drawPatterns[strokeColor]
    }

    // 切换绘制图案的颜色
    const handleChangePatternColor = (currentStrokeColor: string, prevStrokeColor: string) => {
      // 如果当前工具栏还存在操作则关闭当前工具栏的操作后再删除
      if (state.activeToolbarKey) handleToggleToolBarKey(undefined)
      if (state.drawPatterns[currentStrokeColor]) {
        state.drawPatterns[currentStrokeColor].pattern.setOptions({ strokeColor: prevStrokeColor })
        state.drawPatterns[prevStrokeColor] = { ...state.drawPatterns[currentStrokeColor] }
      }
      // 并删除原来的绘制的图案
      delete state.drawPatterns[currentStrokeColor]
    }

    // 每次打开操作框时默认选中画图key
    watch(
      () => props.strokeColor,
      (nextValue, prevValue) => {
        if (nextValue && state.drawPatterns?.[nextValue]?.pattern)
          state.drawPatterns[nextValue].pattern?.setOptions({
            strokeWeight: state.drawPatterns[nextValue].pattern?.getOptions().strokeWeight + 2
          })
        if (prevValue && state.drawPatterns?.[prevValue]?.pattern)
          state.drawPatterns[prevValue].pattern?.setOptions({
            strokeWeight: state.drawPatterns[prevValue].pattern?.getOptions().strokeWeight - 2
          })
        if (props.strokeColor && props.visible && state.activeToolbarKey !== 'draw') {
          handleClickDrawPattern()
        }
      }
    )

    // 每次打开操作框时默认选中画图key
    watch(
      () => props.visible,
      (nextValue) => {
        if (nextValue && state.activeToolbarKey !== 'draw') handleClickDrawPattern()
      }
    )

    // onMounted(async () => {
    //   if (!globalState?.provinceSelectList?.value?.length) {
    //     state.loading = true
    //     // 获取省市区下拉列表
    //     await store.dispatch('global/GetRegionSelectTreeList')
    //     state.loading = false
    //   }
    // })

    expose({
      eventState,
      drawPatterns: state.drawPatterns,
      initDrawPattern: handleInitDrawPattern,
      clearToggleToolBarKey: () => handleToggleToolBarKey(undefined),
      setPolylinePath: eventMethod.handleChangeDrawPolylinePath,
      setContactPointPolyline: eventMethod.handleContactPointAtPolyline,
      toDeletePattern: handleDeletePattern,
      toChangePatternColor: handleChangePatternColor
    })

    return () =>
      props.visible && (
        <ElSpace class={styles['map-toolbar']} spacer="|">
          <ElTooltip effect="light" content="全屏" teleported={false}>
            <ElButton
              text
              plain
              type={state.fullScreen ? 'primary' : 'default'}
              onClick={handleToggleToolBarFullFrameKey}
            >
              <AliIcon type="icon-quyuguanli-quanfu" />
            </ElButton>
          </ElTooltip>
          {/* <ElPopover
            width={500}
            trigger="click"
            teleported={false}
            onHide={() => handleToggleToolBarKey(undefined)}
            v-slots={{
              reference: () => (
                <ElButton
                  text
                  plain
                  type={state.activeToolbarKey === 'position' ? 'primary' : 'default'}
                  onClick={() => handleToggleToolBarKey('position')}
                >
                  <ElTooltip effect="light" content="行政区" teleported={false}>
                    <AliIcon type="icon-quyuguanli-tubiao2" />
                  </ElTooltip>
                </ElButton>
              )
            }}
          >
            <ElTabs v-model={state.activeRegionTabKey}>
              <ElTabPane label="省级" name="province">
                <ElSkeleton animated rows={5} loading={state.loading} />
                <ElSpace wrap>
                  {globalState?.provinceSelectList?.value?.map((item: ProvinceEnum) => (
                    <ElLink
                      underline={false}
                      key={item?.id}
                      type={state.activeProvince?.id === item?.id ? 'primary' : undefined}
                      onClick={() => handleChangeActiveProvince(item)}
                    >
                      {item?.provinceName}
                    </ElLink>
                  ))}
                </ElSpace>
              </ElTabPane>
              <ElTabPane
                label="市级"
                name="city"
                disabled={!globalState?.citySelectList?.value?.length}
              >
                <ElSpace wrap>
                  {globalState?.citySelectList?.value?.map((item: CityEnum) => (
                    <ElLink
                      underline={false}
                      key={item?.id}
                      type={state.activeCity?.id === item?.id ? 'primary' : undefined}
                      onClick={() => handleChangeActiveCity(item)}
                    >
                      {item?.cityName}
                    </ElLink>
                  ))}
                </ElSpace>
              </ElTabPane>
              <ElTabPane
                label="区级"
                name="area"
                disabled={!globalState?.areaSelectList?.value?.length}
              >
                <ElSpace wrap>
                  {globalState?.areaSelectList?.value?.map((item: AreaEnum) => (
                    <ElLink
                      underline={false}
                      key={item?.id}
                      type={state.activeArea?.id === item?.id ? 'primary' : undefined}
                      onClick={() => handleChangeActiveArea(item)}
                    >
                      {item?.districtName}
                    </ElLink>
                  ))}
                </ElSpace>
              </ElTabPane>
            </ElTabs>
          </ElPopover> */}
          <ElTooltip effect="light" content="画图" teleported={false}>
            <ElButton
              text
              plain
              onClick={handleClickDrawPattern}
              type={state.activeToolbarKey === 'draw' ? 'primary' : 'default'}
            >
              <AliIcon type="icon-quyuguanli-tubiao3" />
            </ElButton>
          </ElTooltip>
          <ElTooltip effect="light" content="编辑图形" teleported={false}>
            <ElButton
              text
              plain
              onClick={handleClickEditPattern}
              type={state.activeToolbarKey === 'editGraphics' ? 'primary' : 'default'}
            >
              <AliIcon type="icon-quyuguanli-tubiao4" />
            </ElButton>
          </ElTooltip>
          <ElTooltip effect="light" content="裁剪" teleported={false}>
            <ElButton
              text
              plain
              type={state.activeToolbarKey === 'crop' ? 'primary' : 'default'}
              onClick={handleClickCropPattern}
            >
              <AliIcon type="icon-quyuguanli-tubiao5" />
            </ElButton>
          </ElTooltip>
          <ElTooltip effect="light" content="连线" teleported={false}>
            <ElButton
              text
              plain
              type={state.activeToolbarKey === 'contactLink' ? 'primary' : 'default'}
              onClick={handleClickContactPattern}
            >
              <ElIcon>
                <svg
                  class="icon"
                  viewBox="0 0 1024 1024"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  p-id="3599"
                  width="200"
                  height="200"
                >
                  <path
                    d="M906.32127 511.620741c0 54.179894-43.343915 97.52381-97.52381 97.523809-43.343915 0-81.269841-27.089947-92.10582-65.015873 0-5.417989-5.417989-10.835979-10.835979-10.835979h-384.677248c-5.417989 0-10.835979 5.417989-10.835979 10.835979-16.253968 54.179894-75.851852 75.851852-124.613757 59.597884s-81.269841-75.851852-65.015873-124.613757 75.851852-75.851852 124.613757-59.597883c32.507937 5.417989 54.179894 32.507937 65.015873 59.597883 0 5.417989 5.417989 10.835979 10.835979 10.835979h384.677248c5.417989 0 10.835979-5.417989 10.835979-10.835979 16.253968-54.179894 75.851852-81.269841 124.613757-59.597883 37.925926 10.835979 65.015873 48.761905 65.015873 92.10582z"
                    p-id="3600"
                  ></path>
                </svg>
              </ElIcon>
            </ElButton>
          </ElTooltip>
          {/* <ElTooltip effect="light" content="撤销（暂未开放）" teleported={false}>
            <ElButton
              text
              plain
              disabled
              onClick={() => handleToggleToolBarKey('revoke')}
              type={state.activeToolbarKey === 'revoke' ? 'primary' : 'default'}
            >
              <AliIcon type="icon-quyuguanli-tubiao7" />
            </ElButton>
          </ElTooltip>
          <ElTooltip effect="light" content="恢复（暂未开放）" teleported={false}>
            <ElButton
              text
              plain
              disabled
              onClick={() => handleToggleToolBarKey('recover')}
              type={state.activeToolbarKey === 'recover' ? 'primary' : 'default'}
            >
              <AliIcon type="icon-quyuguanli-tubiao8" />
            </ElButton>
          </ElTooltip> */}
          <ElPopover
            width={300}
            trigger="click"
            teleported={false}
            {...{ onHide: () => handleToggleToolBarKey(undefined) }}
            v-slots={{
              reference: () => (
                <ElButton
                  text
                  plain
                  type={state.activeToolbarKey === 'tips' ? 'primary' : 'default'}
                  onClick={() => handleToggleToolBarKey('tips')}
                >
                  <ElTooltip effect="light" content="使用说明" teleported={false}>
                    <AliIcon type="icon-quyuguanli-tubiao10" />
                  </ElTooltip>
                </ElButton>
              )
            }}
          >
            <ElDescriptions column={1}>
              <ElDescriptionsItem label="工具栏使用说明" />
              <ElDescriptionsItem label="全屏">全屏展示当前页面</ElDescriptionsItem>
              {/* <ElDescriptionsItem label="行政区">
                选择行政区域，系统自动画图，可在行政区域图形的基础上做二次编辑
              </ElDescriptionsItem> */}
              <ElDescriptionsItem label="画图">在原图形的基础上添加图形</ElDescriptionsItem>
              <ElDescriptionsItem label="编辑图形">
                可拖拽图形边框点来调整图形，或者鼠标右键边框点进行点的删除
              </ElDescriptionsItem>
              <ElDescriptionsItem label="裁剪">挖洞，裁剪掉指定区域的图形</ElDescriptionsItem>
              <ElDescriptionsItem label="连线">点击灯杆，自动连成线</ElDescriptionsItem>
            </ElDescriptions>
          </ElPopover>
        </ElSpace>
      )
  }
})
